//
//  gastos.m
//  prototipoEcoFriends
//
//  Created by mayraDonaji on 9/20/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "gastos.h"
#import "configurarGastos.h"
#import "Gasto.h"


@implementation gastos

@synthesize gastoEnGas, gastoEnLuz, gastoEnAgua, totalGasto;
@synthesize irAMainDeMisG, irAConfDeMisG;
@synthesize meses, month, year, nextMonthBt, prevMonthBt;
@synthesize gastoActual;
// CoreData properties
@synthesize fetchedResultsController, managedObjectContext;

// Methods to dismiss the keyboard

-(BOOL) textFieldShouldReturn: (UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}

-(IBAction) backgroundTouched:(id)sender {
	[self dismissKeyboard];
}

-(void) dismissKeyboard {
	[gastoEnGas resignFirstResponder];
	[gastoEnLuz resignFirstResponder];
	[gastoEnAgua resignFirstResponder];
	
	[self calculateExpenses];
}

// Method(s) for calculating total expenses

-(void) calculateExpenses {
	NSDecimalNumber *gas = [gastoEnGas.text length] > 0 ? [NSDecimalNumber decimalNumberWithString:gastoEnGas.text] : [NSDecimalNumber zero];
	NSDecimalNumber *luz = [gastoEnLuz.text length] > 0 ? [NSDecimalNumber decimalNumberWithString:gastoEnLuz.text] : [NSDecimalNumber zero];
	NSDecimalNumber *agua = [gastoEnAgua.text length] > 0 ? [NSDecimalNumber decimalNumberWithString:gastoEnAgua.text] : [NSDecimalNumber zero];
	NSLog(@"Calculating the total");
	NSDecimalNumber *total = [gas decimalNumberByAdding:[luz decimalNumberByAdding:agua]];
	NSLog(@"Total calculatoed");
	totalGasto.text = [NSString stringWithFormat:@"%@",total];
	NSLog(@"Text setted");
}

// Methods for showing the decimal points
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	
    double currentValue = [textField.text doubleValue];
    double cents = round(currentValue * 100.0f);
	
    if ([string length]) {
        for (size_t i = 0; i < [string length]; i++) {
            unichar c = [string characterAtIndex:i];
            if (isnumber(c)) {
                cents *= 10;
                cents += c - '0'; 
            }            
        }
    } else {
        // back Space
        cents = floor(cents / 10);
    }
	
    textField.text = [NSString stringWithFormat:@"%.2f", cents / 100.0f];
    return NO;
	
}

// Method(s) for the month picker
-(IBAction) nextMonth:(id)sender {
	[self saveActualExpense];
	//if (currentMonth == maxMonth && currentYear == maxYear) return;
	meses = [NSArray arrayWithObjects:@"Enero", @"Febrero", @"Marzo", @"Abril", @"Mayo", @"Junio", @"Julio", @"Agosto", @"Septiembre", @"Octubre", @"Noviembre", @"Diciembre", nil];
	currentMonth++;
	if (currentMonth > 12) {
		currentMonth = 1;
		currentYear++;
		year.text = [NSString stringWithFormat:@"%d", currentYear];
	}
	month.text = [meses objectAtIndex:currentMonth-1];
	if (currentMonth == maxMonth && currentYear == maxYear) nextMonthBt.enabled = NO;
	[self displayCurrentData];
	
}

-(IBAction) prevMonth:(id)sender{
	NSLog(@"Antes del SaveACtualExpense");
	[self saveActualExpense];
	NSLog(@"Despues del SaveActualExpense");
	meses = [NSArray arrayWithObjects:@"Enero", @"Febrero", @"Marzo", @"Abril", @"Mayo", @"Junio", @"Julio", @"Agosto", @"Septiembre", @"Octubre", @"Noviembre", @"Diciembre", nil];
	currentMonth--;
	if (currentMonth < 1) {
		currentMonth = 12;
		currentYear--;
		year.text = [NSString stringWithFormat:@"%d", currentYear];
	}
	month.text = [meses objectAtIndex:currentMonth-1];
	if (currentMonth < maxMonth && currentYear <= maxYear) nextMonthBt.enabled = YES;
	[self displayCurrentData];
}

// Methods for ABC of expenses
-(void) addGasto {
	Gasto *g = (Gasto *)[NSEntityDescription insertNewObjectForEntityForName:@"Gasto" inManagedObjectContext:managedObjectContext];
	g.month = [NSNumber numberWithInt:currentMonth];
	g.year = [NSNumber numberWithInt:currentYear];
	g.agua = gastoEnAgua.text;
	g.luz = gastoEnLuz.text;
	g.gas = gastoEnGas.text;
	
	NSError *error;
	if (![managedObjectContext save:&error]) {
		// Handle the error.
	}
}

-(void) saveActualExpense {

	
	
	NSLog(@"Starting saveACtualExpense");
	NSLog(@"Current Month: %d", currentMonth);
	NSLog(@"Current Year:  %d", currentYear);
	if (gastoActual == nil 
		&& ([gastoEnAgua.text length] > 0 || [gastoEnLuz.text length] > 0 || [gastoEnGas.text length] > 0)
		) [self addGasto];
	else {
		NSFetchRequest *request = [[NSFetchRequest alloc] init];
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"Gasto" inManagedObjectContext:managedObjectContext];
		[request setEntity:entity];
		
		NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(year == %@) AND (month == %@)", [NSNumber numberWithInt:currentYear], [NSNumber numberWithInt:currentMonth]];
		[request setPredicate:predicate];
		
		NSError *error;
		NSMutableArray *items = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
		
		if ([items count] <= 0) return;
		
		gastoActual = (Gasto *)[items objectAtIndex:0];
		
		NSLog(@"Current Month 2: %d", currentMonth);
		NSLog(@"Current Year 2:  %d", currentYear);
		gastoActual.month = [NSNumber numberWithInt:currentMonth];
		NSLog(@"Actual month set");
		gastoActual.year  = [NSNumber numberWithInt:currentYear];
		NSLog(@"Actual year set");
		gastoActual.agua  = gastoEnAgua.text;
		NSLog(@"Gasto Agua set");
		gastoActual.luz   = gastoEnLuz.text;
		NSLog(@"Gasto Luz set");
		gastoActual.gas   = gastoEnGas.text;
		NSLog(@"Gasto Gas set");
		if (![managedObjectContext save:&error]) {
			// Handle the error.
		}
		
		[items release];
		[request release];
	}
	NSLog(@"Ending saveActualExpense");
}

-(void) displayCurrentData {
	// Retrieve data
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Gasto" inManagedObjectContext:managedObjectContext];
	[request setEntity:entity];
	
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(year == %@) AND (month == %@)", [NSNumber numberWithInt:currentYear], [NSNumber numberWithInt:currentMonth]];
	[request setPredicate:predicate];
	
	NSError *error;
	NSMutableArray *items = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
	
	
	gastoActual = nil;
	
	if (items != nil && [items count] > 0) {
		gastoActual = (Gasto *)[items objectAtIndex:0];
		NSLog(@"Gasto");
		NSLog(@"%@", gastoActual.gas);
		gastoEnGas.text = gastoActual.gas;
		
		NSLog(@"%@", gastoActual.luz);
		NSLog(@"%@", gastoActual.agua);
		gastoEnLuz.text = gastoActual.luz;
		gastoEnAgua.text = gastoActual.agua;
		[self calculateExpenses];
	} else {
		gastoEnGas.text = @"";
		gastoEnLuz.text = @"";
		gastoEnAgua.text = @"";
		totalGasto.text = @"";
	}
	
	[items release];
	[request release];
}

// Initialization
- (void)viewDidLoad {
    [super viewDidLoad];
	meses = [NSArray arrayWithObjects:@"Enero", @"Febrero", @"Marzo", @"Abril", @"Mayo", @"Junio", @"Julio", @"Agosto", @"Septiembre", @"Octubre", @"Noviembre", @"Diciembre", nil];
	
	// Get current month and year
	NSDate *now = [NSDate date];
	NSDateFormatter *f = [[[NSDateFormatter alloc] init] autorelease];
	[f setDateFormat:@"MM"];
	maxMonth = [[f stringFromDate:now] intValue];
	currentMonth = maxMonth;
	month.text = [meses objectAtIndex:currentMonth-1];
	
	[f setDateFormat:@"yyyy"];
	maxYear = [[f stringFromDate:now] intValue];
	currentYear = maxYear;
	year.text = [NSString stringWithFormat:@"%ld", currentYear];
	nextMonthBt.enabled = NO;
	
	[self displayCurrentData];
	
}

-(IBAction) irAMainDeMisG:(id)sender{
	[self addGasto];
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction) irAConfDeMisG:(id)sender{
	configurarGastos * confG = [[configurarGastos alloc]initWithNibName: nil bundle:nil];
	confG.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;	
	[self presentModalViewController:confG animated:YES];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
